package com.shty.wd.utils.module.related;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.shty.wd.utils.module.IOTools.IOUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonParse {

	
	// Given a search data, transform it into a ResultData
	public ResultData parse(String data){
		 
		JSONObject object = JSONObject.fromObject(data);			
		
		String projectId= object.getString("projectId");			
		String webSite = object.getString("webSite") ;
		JSONArray friendsList = object.getJSONArray("friendsList");
		List<Entity> searchList = getEntityList(friendsList);
		
		return new ResultData(projectId, webSite, searchList);	
	}

	// Given a list of JSONObject, transform it into a list of Entity
	public List<Entity> getEntityList(JSONArray searchResultList){
		List<Entity> list = new ArrayList<>() ;
		for (int i = 0; i < searchResultList.size(); i++){
			JSONObject oneSearchResult = searchResultList.getJSONObject(i) ;
			Entity entity =  getEntity(oneSearchResult) ;
			list.add(entity);
		}
		return list ;
	}
	
	// Given a JSONObject, transform it into an Entity
	public Entity getEntity(JSONObject entityJson){
		Entity entity = new Entity();
		Set<String> feature = entityJson.keySet();
		for (String str : feature) {
			
			entity.getResult().put(str,entityJson.optString(str)) ;
		}
		return entity ;
	}

	public List<ResultData> parseFormDir(String path) {
		File file = new File(path);
		List<ResultData> list = new ArrayList<>();
		if (!file.exists()) return null;
		File[] dirs = file.listFiles();
		for (File f : dirs) {
			if (f.getName().equals("facebook")) {
				JSONArray friendsList = JSONArray.fromObject(IOUtil.readfromDir(path + "/facebook"));
				List<Entity> searchList = getEntityList(friendsList);
				list.add(new ResultData(System.currentTimeMillis() + "", "facebook", searchList));
			}
			if (f.getName().equals("lnk")) {
				JSONArray friendsList = JSONArray.fromObject(IOUtil.readfromDir(path + "/lnk"));
				List<Entity> searchList = getEntityList(friendsList);
				list.add(new ResultData(System.currentTimeMillis() + "", "linkedIn", searchList));
			}
		}
		return list;
	}
	
	
	public Entity parseEntity(String data){
		 
		JSONObject object = JSONObject.fromObject(data);		
		Entity entity = getEntity(object) ;
		return entity;	
	}
}
